﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace XRpgLibrary.ExtensionMethods
{
    public static class RectangleExtension
    {

        public static Rectangle IntersectionRectangle(this Rectangle thisRect,
            Rectangle otherRect)
        {
            if (thisRect.Intersects(otherRect))
            {
                int left = Math.Max(thisRect.Left, otherRect.Left);
                int top = Math.Max(thisRect.Top, otherRect.Top);
                return new Rectangle(
                    left,
                    top,
                    Math.Min(thisRect.Right, otherRect.Right) - left,
                    Math.Min(thisRect.Bottom, otherRect.Bottom) - top
                    );
            }

            return Rectangle.Empty;
        }

        public static Vector2 IntersectionVector(this Rectangle thisRect, Rectangle otherRect)
        {
            if (thisRect.Intersects(otherRect))
            {
                return new Vector2(
                    Math.Min(thisRect.Right, otherRect.Right) - Math.Max(thisRect.Left, otherRect.Left),
                    Math.Min(thisRect.Bottom, otherRect.Bottom) - Math.Max(thisRect.Top, otherRect.Top)
                    );
            }

            return Vector2.Zero;
        }

        public static Vector2 IntersectionRepelVector(this Rectangle thisRect, Rectangle otherRect)
        {
            if (thisRect.Intersects(otherRect))
            {
                int signX = thisRect.Right > otherRect.Right ? -1 : 1;
                int signY = thisRect.Top > otherRect.Top ? -1 : 1;

                float x = Math.Min(thisRect.Right, otherRect.Right) - Math.Max(thisRect.Left, otherRect.Left);
                float y = Math.Min(thisRect.Bottom, otherRect.Bottom) - Math.Max(thisRect.Top, otherRect.Top);
                
                if (Math.Abs(x) < Math.Abs(y))
                    return new Vector2(x * signX, 0);
                if (Math.Abs(y) < Math.Abs(x))
                    return new Vector2(0, y * signY);

                return new Vector2(x * signX, y * signY);
            }

            return Vector2.Zero;
        }

        public static Rectangle Clone(this Rectangle rect)
        {
            return new Rectangle(rect.X, rect.Y, rect.Width, rect.Height);
        }
    }
}
